<template>
  <view class="page">
    <view class="authorize_content" v-if="isCanUse">
      <view class="authorize_pic">
        <image src="/static/img/logo.png"></image>
        <view class="authorize_title"></view>
        <view class="authorize_text">
          您暂未授权3D拓客宝小程序获取您的信息，竟无法正常使用小程序的功能。如果要正常使用，请点击“授权”按钮，打开头像，昵称等信息的授权
        </view>
      </view>
      <button type="primary" class="authorize_true" open-type="getUserInfo" withCredentials="true" lang="zh_CN"
        @getuserinfo="GetUserInfo">授权登陆</button>
      <button type="primary" plain="true" class="authorize_false" @click="handleclose">取消</button>
    </view>
    <view class="authorize_content" v-else="isCanUse">
      <view class="authorize_pic">
        <image src="/static/img/logo.png"></image>
        <view class="authorize_title"></view>
      </view>
      <button type="primary" class="authorize_true" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">微信快捷登陆</button>
      <view class="authorize_text" style="padding: 25rpx 44rpx;font-size: 24rpx;">
        若您的微信手机号未注册，将为您直接注册，注册即视为同意<navigator hover-class="none" url="/pagesA/tos/tos" style="color: #007AFF;display: inline;">《拓客宝用户服务条款》</navigator>
      </view>
    </view>
  </view>
</template>

<script>
  import {
    requestAll
  } from '@/http/api'
  export default {
    data() {
      return {
        SessionKey: '',
        OpenId: '',
        nickName: null,
        avatarUrl: null,
        isCanUse: true, //默认为true
        phone: ''
      };
    },
    methods: {
      onLoad() { //默认加载login
        this.login(); // 调用登陆模块获取token
        uni.getStorage({
          key: 'isCanUse',
          success: (res) => {
            this.isCanUse = res.data
          }
        })
      },
      GetUserInfo() { //第一授权获取用户信息===》按钮触发
        let _this = this;
        uni.getUserInfo({
          provider: 'weixin',
          success: function(infoRes) {
            _this.nickName = infoRes.userInfo.nickName; //昵称
            _this.avatarUrl = infoRes.userInfo.avatarUrl; //头像
						uni.setStorageSync('userInfo', infoRes.userInfo)
            try {
              uni.setStorage({
                key: 'isCanUse',
                data: false,
                success: (res) => {
                  _this.isCanUse = false
                }
              })
              // _this.updateUserInfo();
            } catch (e) {}
          },
          fail(res) {
            console.log('获取失败');
          }
        });
      },

      //登录
      login() {
        let _this = this;
        // 1.wx获取登录用户code
        uni.login({
          provider: 'weixin',
          success: function(loginRes) {
            let code = loginRes.code;
            let formData = {
              random_str: _this.$dokey.getRandom(), // 字符串
              timestamp: _this.$dokey.getTime(), // 时间戳
              method: 'user.wx.auth', // 路径
              sign: _this.$md5(_this.$dokey.secretdate('user.wx.auth')),
              js_code: code
            }
            requestAll(formData).then(resp => {
              let wxAuth = resp.response_data.wx_data
              uni.setStorageSync('wxAuth', wxAuth) // 知道执行这个方法 就把openid和session_key 存到缓存里  后面如果使用微信得相关API可以直接调取使用
            }).catch(err => {
              console.log(err);
            })
          },
        });
      },
      getPhoneNumber(e) {
        let data = {
          encrypted_data: e.detail.encryptedData,
					openid: uni.getStorageSync('wxAuth').openid,
          iv: e.detail.iv,
          session_key: uni.getStorageSync('wxAuth').session_key,
          method: 'user.wx.get.phone',
          random_str: this.$dokey.getRandom(), // 字符串
          timestamp: this.$dokey.getTime(), // 时间戳
          sign: this.$md5(this.$dokey.secretdate('user.wx.get.phone')),
        }
        requestAll(data).then(resp => {
          let _this = this
          this.phone = resp.response_data.phoneNumber
          uni.checkSession({
            success: res => { 
              uni.login({
                provider: 'weixin',
                success:(loginRes)=> {
                  let code = loginRes.code;
                  let formData = {
                    random_str: _this.$dokey.getRandom(), // 字符串
                    timestamp: _this.$dokey.getTime(), // 时间戳
                    method: 'user.wx.auth', // 路径
                    sign: _this.$md5(_this.$dokey.secretdate('user.wx.auth')),
                    js_code: code
                  }
                  requestAll(formData).then(resp => {
                    if (resp.response_data.user_data) { // 这里判断是否已经是注册且登陆状态，如果是获取token ，将数据存到myInfo中
                      uni.setStorageSync('token', resp.response_data.user_data.token)
                      uni.setStorage({
                        key: 'myInfo',
                        data: resp.response_data.user_data,
                        success: (res1) => {
                          uni.redirectTo({
                            url: "/pages/myWeb/myWeb"
                          })
                        }
                      })           
                    } else {
                      uni.navigateTo({
                        url: '/pagesA/login/login?phone=' + this.phone,
                        fail: (err) => {
                          console.log(err);
                        }
                      })
                    }   
                  }).catch(err => {
                    console.log(err);
                  })
                },
              });             
            }
          })
        }).catch(err => {
          console.log(err);
        })
      },
      handleLogin() {
        uni.navigateTo({
          url: '../login/login'
        })
      },
      handleclose() {
        uni.navigateBack({
          delta: 1
        })
      }
    }
  }
</script>
<style lang="scss">
  .authorize_pic {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-bottom: 150rpx;
    padding-top: 150rpx;


    image {
      margin: 0 50rpx;
      width: 200rpx;
      height: 200rpx;
      border-radius: 100%;
    }

    .authorize_title {
      margin-top: 56rpx;
      font-size: 36rpx;
      font-weight: 600;
    }

    .authorize_text {
      font-size: 26rpx;
      color: #3e3e3e;
      padding: 16rpx 50rpx;
      font-weight: normal;
    }
  }

  .authorize_true {
    width: 690rpx;
    font-size: 30rpx;

  }

  .authorize_false {
    margin-top: 30rpx;
    width: 690rpx;
    font-size: 30rpx;

  }
</style>
